package com.oda.colza;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.activity.colza.R;
import com.activity.colza.ResultatListActivity;
import com.oda.camera.ODA_Capture_ctivity;
import com.oda.camera.TakeActivity;
import com.oda.camera.util.CameraUtils;
import com.oda.camera.util.LoadResultat;
import com.oda.camera.util.SaveResultat;
import com.oda.colza.util.SystemUiHider;
import com.oda.download.DownloadResult;
import com.oda.resultats.ODA_AllRes_Activity;
import com.oda.resultats.ODA_Res_Activity;
import com.oda.resultats.util.Resultat;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class LaunchscreenActivity extends Activity {
	
	/**
	 * Login and pass for test
	 */
	private final String login="android";
	private final String pass="android";

	/**
	 * 
	 * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
	 */
	private static final boolean AUTO_HIDE = true;

	/**
	 * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
	 * 
	 */
	private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

	/**
	 * If set, will toggle the system UI visibility upon interaction. Otherwise,
	 * will show the system UI visibility upon interaction.
	 */
	private static final boolean TOGGLE_ON_CLICK = true;

	/**
	 * The flags to pass to {@link SystemUiHider#getInstance}.
	 */
	private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;

	/**
	 * The instance of the {@link SystemUiHider} for this activity.
	 */
	private SystemUiHider mSystemUiHider;

	/**
	 * Path for pictures
	 */
	private String writePhotoPath;
	
	/**
	 * UI
	 */
	private View contentView;
	private View loginView;
	
	private static final int PROGRESS_BAR_TYPE = 0;
	private ProgressDialog pDialog;
	Resultat res;
	/**
	 * The uri to get result
	 */
	private static String URI_RESULT="http://192.168.137.26:8080/wsRestImage/rest/colza/resultat/";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_launchscreen);

		//final View controlsView = findViewById(R.id.fullscreen_content_controls);
		contentView = findViewById(R.id.fullscreen_content);
		loginView = findViewById(R.id.login_form);
		loginView.bringToFront();
		
		// Set up an instance of SystemUiHider to control the system UI for
		// this activity.
		mSystemUiHider = SystemUiHider.getInstance(this, contentView,
				HIDER_FLAGS);
		mSystemUiHider.setup();
	}

	/**
	 * function to show all results
	 * @param v
	 */
	public void allResults(View v) {
		Intent intent = new Intent(this, ResultatListActivity.class);
		startActivity(intent);
	}

	/**
	 * function to view Result
	 * @param v
	 */
	public void currentResult(View v) {
		if (AUTO_HIDE) {
			delayedHide(AUTO_HIDE_DELAY_MILLIS);
			v.destroyDrawingCache();
			//get the id of the user
			String idUser="1";
			new GetCurrentData().execute(URI_RESULT+idUser);
					
		}
	}
	
	/**
	 * function to take image
	 * @param v
	 */
	public void captImage(View v) {
		if (AUTO_HIDE) {
			delayedHide(AUTO_HIDE_DELAY_MILLIS);
			Intent intent = new Intent(this, ODA_Capture_ctivity.class);
			startActivity(intent);
		}
	}
	
	/**
	 * function to register
	 * @param v
	 */
	
	public void register(View v){
		
	}
	
	/**
	 * function to cancel and register later
	 * @param v
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	public void registerlater(View v){
		showMain(true);
	}
	
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showMain(final boolean show) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			contentView.setVisibility(View.VISIBLE);
			contentView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							contentView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			loginView.setVisibility(View.VISIBLE);
			loginView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							loginView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			contentView.setVisibility(show ? View.VISIBLE : View.GONE);
			loginView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		// Trigger the initial hide() shortly after the activity has been
		// created, to briefly hint to the user that UI controls
		// are available.
		delayedHide(100);
	}

	/**
	 * Touch listener to use for in-layout UI controls to delay hiding the
	 * system UI. This is to prevent the jarring behavior of controls going away
	 * while interacting with activity UI.
	 */

	Handler mHideHandler = new Handler();
	Runnable mHideRunnable = new Runnable() {
		@Override
		public void run() {
			mSystemUiHider.hide();
		}
	};

	/**
	 * Schedules a call to hide() in [delay] milliseconds, canceling any
	 * previously scheduled calls.
	 */
	private void delayedHide(int delayMillis) {
		mHideHandler.removeCallbacks(mHideRunnable);
		mHideHandler.postDelayed(mHideRunnable, delayMillis);
	}

	/**
	 * Capture image
	 */
	private void dispatchTakePictureIntent() {
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
			startActivityForResult(takePictureIntent,
					CameraUtils.REQUEST_IMAGE_CAPTURE);
		}
	}

	/**
	 * Get the result after taking Pictures
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CameraUtils.REQUEST_IMAGE_CAPTURE
				&& resultCode == RESULT_OK) {
			Intent intent = new Intent(this, ODA_Capture_ctivity.class);
			startActivity(intent);
		}
	}

	
	
	/**
	 * 
	 */
	
	/**
	 * Asynch to Get result
	 */
	class GetCurrentData extends AsyncTask<String, String, InputStream>{
		
		@SuppressWarnings("deprecation")
		protected void onPreExecute() {
			super.onPreExecute();
			showDialog(PROGRESS_BAR_TYPE);
		}

		@Override
		protected InputStream doInBackground(String... urls) {
			try {
				//return new DownloadResult().downloadUrl(urls[0]);
				return new DownloadResult().getUrlData(urls[0]);
			} catch (IOException e) {
				Log.d("TAG", "Unable to retrieve data. URI may be invalid."+e);
				return null;
			} catch (URISyntaxException e) {
				return null;
			} 
			
		}
		
		/**
		 * Updating progress bar
		 * */
		protected void onProgressUpdate(String... progress) {
			// setting progress percentage
			pDialog.setProgress(Integer.parseInt(progress[0]));
		}

		@SuppressWarnings("deprecation")
		@Override
		protected void onPostExecute(InputStream result) {
			Log.d("RESULT", "" + result);			
			res=new DownloadResult().retreiveData(result);
			Log.i("biomasse", ""+res);
			//Resultat res=new Resultat(1, 1, 3.14f, 0.5f, 10f, 1.25f);
			//Save the resultat
			List<Resultat> storeResultat =new ArrayList<Resultat>();
			storeResultat.add(res);
			Log.d("LOAD", "begin");
			SaveResultat saveRes1=new SaveResultat(storeResultat);
			LoadResultat existResultat=new LoadResultat();
			Log.d("LOAD", "end");
			if(!existResultat.isExistFile()){
				Log.d("SAVE", "save1");
				SaveResultat saveRes=new SaveResultat(storeResultat);
			}else{
				for(Resultat r:existResultat.getTheList()){
					storeResultat.add(r);
				}
				Log.d("SAVE", "save2");
				SaveResultat saveRes=new SaveResultat(storeResultat);
			}
			// dismiss the dialog after the file was downloaded			
			dismissDialog(PROGRESS_BAR_TYPE);
			
			Intent intent = new Intent(getApplicationContext(), ODA_Res_Activity.class);
			intent.putExtra("biomasse", res.getBiomasse());
			intent.putExtra("lai", res.getLai());
			intent.putExtra("errorrate", res.getErrorRate());
			intent.putExtra("expazote", res.getExpAzote());
			startActivity(intent);

		}
		
	}
	
	
	/**
	 * The dialod process
	 */
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case PROGRESS_BAR_TYPE: // we set this to 0
			pDialog = new ProgressDialog(this);
			pDialog.setMessage("Checking for result...");
			pDialog.setIndeterminate(false);
			pDialog.setProgressStyle(ProgressDialog.THEME_DEVICE_DEFAULT_DARK);
			pDialog.setCancelable(false);
			pDialog.show();
			return pDialog;
		default:
			return null;
		}
	}
}
